package com.sweet.web;

import io.vertx.core.*;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class StartVerticle extends AbstractVerticle implements RouterVerticle {

  public static void main(String[] args) throws IOException {
    Vertx.vertx().deployVerticle(new StartVerticle(), new DeploymentOptions()
        .setConfig(new JsonObject(new String(Files.readAllBytes(Paths.get("config.json"))))
    ));
  }

  @Override
  public void start() throws Exception {
    super.start();
    JsonArray verticles = config().getJsonArray("verticles");

    List<Future> futures = verticles.stream()
        .map(name -> Future.<String>future(r ->
            vertx.deployVerticle(name.toString(), new DeploymentOptions().setConfig(config()), r))
        ).collect(Collectors.toList());

    CompositeFuture.all(futures).setHandler(res -> {
      Router router = Router.router(vertx);
      routers.forEach(r -> router.route(r.getHttpMethod(), r.getApi()).handler(r.getHandler()));
      System.out.println(routers.size());
      vertx.createHttpServer().requestHandler(router::accept).listen(config().getInteger("port"), server -> {
        if (server.succeeded()) {
          System.out.println("server ok");
        } else {
          server.cause().printStackTrace();
        }
      });
    });
  }

}
